<template>
  <div class="account-module">
    <div class="register">
      <div class="c">
        <el-form
          ref="ruleFormRef"
          :model="ruleForm"
          :rules="rules"
          label-width="150px"
          class="ruleForm"
          :size="formSize"
          status-icon
        >
          <el-form-item label="姓名" prop="realName">
            <div class="hint-input" style="height: 45px;">
              <el-input v-model="ruleForm.realName" />
              <!--<div class="hint">本信息将导入证件制作系统，请务必填写准确</div>-->
            </div>
          </el-form-item>
          <el-form-item label="联系方式(手机)" prop="phone">
            <el-input v-model="ruleForm.phone" placeholder="请输入"/>
            <span class="btn-code" @click="queryUser">查询</span>
          </el-form-item>
          <el-form-item label="性别" prop="sex" v-if="ruleForm.sex">
            {{ruleForm.sex?(ruleForm.sex==='1'?'男':'女'):''}}
          </el-form-item>
          <el-form-item label="选手证件" prop="idType" v-if="ruleForm.idType">
            {{ruleForm.idType === '1' ? '居民身份证' : ruleForm.idType === '2' ? '临时身份证' : ruleForm.idType === '3' ? '港澳居民来往内地通行证' : ruleForm.idType === '4' ? '台湾居民来往大陆通行证' : ruleForm.idType === '5' ? '护照/其他' : ''}}
          </el-form-item>
          <el-form-item label="证件号码" prop="idCard" v-if="ruleForm.idCard">
            {{baseService.hideIdCard(ruleForm.idCard)}}
          </el-form-item>
          <el-form-item label="电子邮箱" v-if="ruleForm.email">
            {{ruleForm.email}}
          </el-form-item>
          <el-form-item label="上传领队授权书" prop="empower" v-if="userType==='2'">
            <el-upload
                class="avatar-uploader"
                :action="baseUrl+'/front/upload'"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
            >
              <div class="image">
                <img v-if="imageUrl" :src="imageUrl" class="img" />
                <div v-else class="upload">
                  <img src="@/assets/common/upload.png">
                  <div class="text">上传领队授权书</div>
                </div>
              </div>
              <div class="hint">支持JPG/JPEG/PNG/PDF格式，不超过5MB <a target="_blank" style="text-decoration:underline;color: #00a0e9;" @click.stop="downLoad1()">下载模板</a></div>

            </el-upload>
          </el-form-item>

          <el-form-item>
             <div class="btns" style="text-align: left;">
                <el-button type="primary" @click="submitForm(ruleFormRef)" :disabled="btnDisabled">
                {{ userType === '2' ? '添加领队' : (userType === '3' ? '添加指导老师' : '添加选手')}}
                </el-button>
                <el-button @click="resetForm(ruleFormRef)">取消</el-button>
             </div>
          </el-form-item>

        </el-form>
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { reactive, ref } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import baseService from "@/service/baseService";
import {ElMessage, UploadProps} from "element-plus";
import { useRoute, useRouter } from "vue-router";
import app from "@/constants/app";
import {rule} from "postcss";
const route = useRoute();
let router = useRouter();
const baseUrl = app.api;

const uType = route.query.type;
let userType = '';
//添加
if (uType=='1') {
  //存入副领队
  userType = '2';
} else if(uType=='2'){
  //存入指导老师
  userType = '3';
} else {
  //存入选手
  userType = '4';
}
console.log('====', userType)
const imageUrl = ref('')
const formSize = ref("default");
const ruleFormRef = ref<FormInstance>();
const btnDisabled = ref(false);
const ruleForm = reactive({
  realName: "",
  sex: "",
  idType: "",
  idCard: "",
  company: "",
  phone: "",
  email: "",
  header: "",
  empower: "",
  userId: null,
  type: userType
});

const rules = reactive<FormRules>({
  realName: [{ required: true, message: "请输入姓名", trigger: "blur" }],
  sex: [
    {
      required: true,
      message: "请选择性别",
      trigger: "change",
    },
  ],
  idType: [
    {
      required: true,
      message: "请选择证件",
      trigger: "change",
    },
  ],
  idCard: [{ required: true, message: "请输入证件号码", trigger: "blur" }],
  company: [{ required: true, message: "请输入参赛单位", trigger: "blur" }],
  phone: [{ required: true, message: "请输入手机号", trigger: "blur" }],
  empower: [{ required: true, message: "请上传领队授权书", trigger: "blur" }],
});

/**
 * 提交表单-添加领队成员
 * @param formEl
 */
const submitForm = async (formEl: FormInstance | undefined) => {
  if(!ruleForm.userId){
    ElMessage.error('请先查询用户信息');
    return;
  }
  btnDisabled.value = true;
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      baseService
          .post("/front/spteamuser/save", ruleForm)
          .then((res) => {
                if (res.code === 0) {
                  // 跳转到领队主页
                  if(uType === '1') {
                    router.push("/team/index");
                  } else if(uType === '2') {
                    router.push("/space");
                  } else {
                    router.push("/player");
                  }
                } else {
                  ElMessage.error(res.msg);
                }
                btnDisabled.value = false;
              }
          );

    } else {
      console.log("error submit!", fields);
    }
  });
};


/**
 * 查询用户信息
 * @param formEl
 */
const queryUser = async (formEl: FormInstance | undefined) => {
  //姓名不能为空
  if (ruleForm.realName === "") {
    ElMessage.error("姓名不能为空！");
    return;
  }
  //校验手机号不能为空
  if (ruleForm.phone === "") {
    ElMessage.error("手机号不能为空！");
    return;
  }
  baseService
      .post("/front/spuser/queryUser", {
        realName: ruleForm.realName,
        phone: ruleForm.phone,
        roleId: uType
      })
      .then((res) => {
            if (res.code === 0) {
              ruleForm.idType = res.data.idType;
              ruleForm.idCard = res.data.idCard;
              ruleForm.sex  = res.data.sex+'';
              ruleForm.email = res.data.email;
              ruleForm.header = res.data.header;
              ruleForm.userId = res.data.id;
            } else {
              ElMessage.error(res.msg);
            }
          }
      );
};

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
  //router.push("/");
  window.history.go(-1);
};


const handleAvatarSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
  ruleForm.empower = response.data.src;
  imageUrl.value = URL.createObjectURL(uploadFile.raw!)
  if(response.data.showSrc){
    imageUrl.value = response.data.showSrc;
  }
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (!(rawFile.type == 'image/jpeg'||rawFile.type == 'image/png'||rawFile.type == 'image/jpg' || rawFile.type == 'application/pdf')) {
    ElMessage.error('仅支持JPG/JPEG/PNG/PDF格式!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 5) {
    ElMessage.error('授权书不能超过5MB!')
    return false
  }
  return true
}

const downLoad1 = async () => {
  let a = document.createElement('a');
  let evt = document.createEvent('MouseEvents');
  a.download = '领队授权书';
  a.href = '/doc/全国青少年无人机大赛-领队授权书.docx';
  evt.initEvent('click',true,true);
  a.dispatchEvent(evt);
  window.URL.revokeObjectURL(a.href);
}


</script>


<style lang="scss" scoped>
@import "../account/account";

.title-h {
  display: flex;
  align-items: center;
  font-size: 16px;
  font-weight: $font-weight-bold;
  padding: 24px 24px 0px;


  span {
    width: 4px;
    height: 12px;
    background: #00a0e9;
    margin-right: 7px;
  }
}

.account-module .register,
.account-module {
  width: 100%;
  height: auto;
  display: block;
  background: none;

  .c .term-ruleForm {

    padding: 0px;
    margin-top: 10px;
    margin-left: 30px;

    .btn-code {
      width: 98px;
      line-height: 32px;
      background: #EFF6FF;
      border-radius: 4px;
      text-align: center;
      color: $color-primary;
      margin-left: 12px;

    }

    .btns {
      width: 100%;
      margin-left: 275px;
      margin-top: 12px;
      display: block;
    }
  }

  .c .uplods {
    top: 231px;
    display: flex;
    left: 480px;
    right: inherit;
    margin-right: 52px;

    .avatar-uploader {

      margin-right: 52px;
    }
  }
}
</style>
<style lang="scss">
.term-ruleForm {
  .el-input {
    width: 220px;
  }

  .el-form-item--default .el-form-item__label {
    font-weight: $font-weight-bold;
    color: #333;
  }
  .el-radio__inner{
    border-color:#a8abb2;
  }
  .el-button{
    width: 108px;
    height: 38px;
  }

}
</style>
